package com.demo.lab.controller;


import com.demo.lab.entity.base.Result;
import com.demo.lab.service.FileService;
import com.demo.lab.utils.ServletUtil;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file/")
public class FileController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    FileService fileService;

    /**
     * Describe: 文件上传接口
     * Return: Result
     */
    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        String result = fileService.upload(file);
        if (Strings.isNotBlank(result)) {
            return Result.success(0, "上传成功", result);
        } else {
            return Result.failure("上传失败");
        }
    }

    @PostMapping("upload2")
    public Result uploadToPath(@RequestParam("file") MultipartFile file) {
        String result = fileService.upload(file);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("src", "http://localhost:8080/file/download/" + result);
        map.put("title", result);
        if (Strings.isNotBlank(result)) {
            return Result.success(0, "上传成功", map);
        } else {
            return Result.failure("上传失败");
        }
    }


    /**
     * Describe: 文件获取接口
     * Param: id
     * Return: 文件流
     */
    @GetMapping("download/{name}")
    public void download(@PathVariable("name") String name) throws Exception {
        fileService.download(name, ServletUtil.getResponse());
    }

}
